$(function () {
    //初始化选择框
    $("#roleSelect").select2({
        placeholder: "请选择",
        theme: "bootstrap",
        width: '20em',
        ajax: {
            url: "../../v1/role",
            dataType: 'json',
            data: function (params) {
                var query = {rows: 10, page: params.page,sort:'name asc'};
                if (params.term != null && params.term.length > 0) {
                    var str = "name like '*"+params.term+"*' or description like '*"+params.term + "*'";
                    query['search'] = encodeURIComponent(str);
                    query['search_encode'] = true;
                }
                return query;
            },
            processResults: function (data, params) {
                $.each(data.rows, function (i, item) {
                    item.id = item.roleId;
                    item.text = item.name + ' | ' + item.description;
                });
                params.page = params.page || 1;
                return {
                    results: data.rows,
                    pagination: {
                        more: (params.page * 10) < data.total
                    }
                };
            }
        }
    }).on("change",selectChange);
});

/**
 * 修改数据
 */
function editData() {
    toastr.options = {"positionClass": "toast-top-center"};
    var roleId = $("#roleSelect").select2('val');
    if(roleId==null){
        toastr.info("请选择一个角色");
        return;
    }
    var rows = $('#table').bootstrapTable('getSelections');
    var permissionId = $.map(rows,function(item){
        return item.permissionId;
    });
    $.ajax({
        type:'post',
        url:'../../v1/role/'+roleId+'/permission',
        data:{permissionId:JSON.stringify(permissionId)},
        success:function (data) {
            toastr.success("保存成功");
        },error:function (data) {
            if (data.responseJSON && data.responseJSON.error) {
                toastr.error(data.responseJSON.error.message);
            }else{
                toastr.error("系统错误，请稍后重试");
            }
        }
    });
}

/**
 * 选择框的值发生改变时将该角色拥有的权限都选中
 */
function selectChange() {
    $('#table').bootstrapTable('uncheckAll');
    var roleId = $("#roleSelect").select2('val');
    if(roleId==null){
        return;
    }
    $.getJSON("../../v1/role/"+roleId+"/permission",{rows:300,field:'permissionId'},function(data){
        var id = $.map(data.rows,function (item) {
            return item.permissionId;
        });
        $("#table").bootstrapTable("checkBy", {field:"permissionId", values:id});
    });

}
